/**
 *	contains the hosting main loop
**/

var MatchHost = {
	
	//begin the hosting process
	host: function() {
		API.createGame(
			{ playerName: Main.clientInfo.user },
			this._callback
		)
	},
	
	_callback: function(response) {
		var that = MatchHost						//get this function back into the right context
		
		that._gameInfo = JSON.parse(response)		//save the game info returned
		that.hostMainLoop("start")					//begin!
	},
	
	
/**
 *	this checks the status of the game we are hosting.
 *	serves 2 functions:
 *		-	check in with the server, so it knows we are actively waiting, 
 *			and does not delete the game.
 *		-	check if the game has matched us with an opponent yet!
**/
	hostMainLoop: function(action) {
		var that = this
		if (action === "start") {
			//move to send to the server
			var move = { gameId: this._gameInfo.gameId }
			
			//run this callback on successful return
			var callback = function(payload) {
				var newGame = JSON.parse(payload)
				if (newGame.players.length === 2) {					//if 2 players have joined, we're ready to go!
					that.hostMainLoop("stop")
					
					//var playerName = that._nameHolder.value			//remember the player name for later
					//GameChooser.beginGame(newGame, playerName)
					
					Main.goTo('GamePage')
					Game.setUpGame(newGame)
				}
			}
			
			//set up the interval
			this._hostCheckInterval = setInterval(function() {
				API.checkGameStatus( move, callback )
				console.log("checking for opponent...")
			}, 1000)
		
		} else if (action === "stop") {

			//clear the interval loop, if it exists
			if (this._hostCheckInterval) {
				clearInterval(this._hostCheckInterval)
			}
		}
	}
	
}